package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.csvreader.CsvReader;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.contant.RsSteppedPriceConstant;
import com.yuanda.erp9.syn.entity.CmsBrandsTempEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.enums.*;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.poi.AvnetCsvData;
import com.yuanda.erp9.syn.poi.RsCNCsvData;
import com.yuanda.erp9.syn.poi.RsHkCsvData;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.pojo.CmsPricesPojo;
import com.yuanda.erp9.syn.service.erp9.BrandService;
import com.yuanda.erp9.syn.service.erp9.RsDataImportService;
import com.yuanda.erp9.syn.service.erp9.SupplierService;
import com.yuanda.erp9.syn.util.*;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


@Service
@Slf4j
public class RsDataImportServiceImpl extends RsSaveImpl implements RsDataImportService {

    @Resource
    private BrandService brandService;

    @Resource
    private SupplierService supplierService;

    // 供应商名称
    private static final String SUPPLIER = "RS Components";

    // 供应商id
    private static final String SUPPLIER_ID = "US000000044";

    protected static CacheUtil.ObjectCache rsHKData = CacheUtil.objectInit(CachePrefixEnum.RS_HK_DATA.getKey());

    private static ConcurrentHashMap<String, AtomicInteger> mapCNHK = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<String, AtomicInteger> mapHK = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<String, AtomicInteger> mapCN = new ConcurrentHashMap<>();

    /**
     * 数据插入
     *
     * @param fileCNPath 中国文件路径
     * @param fileHKPath 香港文件路径
     */
    @Override
    public void csvDataInsert(String fileCNPath, String fileHKPath) throws InterruptedException, IOException {
        HashSet<String> HispData = new HashSet<>();//存储hisp数据结果集
        // 处理供应商信息，缓存中没有当前供应商时添加信息到数据库和缓存中
        Integer supplierId = suppliersCache.get(SUPPLIER);
        if (supplierId == null) {
            // 插入供应商数据
            supplierId = supplierService.insertSupplier(SUPPLIER_ID, SUPPLIER);
        }
        if (StringUtils.isEmpty(fileCNPath) || StringUtils.isEmpty(fileHKPath)) {
            return;
        }
        Master<CmsGoodsPojo> objectMaster = new Master<>(supplierId, null, SourceEnum.DATA_PACKAGE.getCode());
        if (fileHKPath.endsWith("rs_components_HK-cn_b1b.csv")) {//香港数据包数据不存入库
            log.info("rs香港数据导入开始");
            Boolean isCN = false; //香港数据包 标识
            CsvReader csvReader = null;
            csvReader = new CsvReader(fileHKPath, ',');
            // 跳过表头(相当于读取完了表头)
            csvReader.readHeaders();
            // 读取每行的内容
            while (csvReader.readRecord()) {
                try {
                    // 获取当前行的所有数据(数组形式)
                    String[] values = csvReader.getValues();
                    RsHkCsvData rsHkCsvData = RsHkCsvData.toRsHkCsvDataFormat(values);
                    if (rsHkCsvData == null) {
                        continue;
                    }
                    CmsGoodsPojo cmsGoodsPojo = insertHKDataToDatabase(rsHkCsvData, isCN, supplierId);
                    if (cmsGoodsPojo != null) {
                        //对象存入map
                        rsHKData.put(cmsGoodsPojo.getCmsGoodsEntity().getGoodid(), cmsGoodsPojo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            log.info("rs香港数据导入结束");
        }
        mapHK.clear();//清空内存
        if (fileCNPath.endsWith("rs_components_cn_b1b.csv")) {//中国数据
            // 读取csv数据
            File file = new File(fileCNPath);
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                log.info("rs中国数据导入开始");
                InputStreamReader read = new InputStreamReader(new FileInputStream(file));
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineText = null;
                Integer min = 1;
                Boolean isCN = true; //中数据包含的英国数据 标识
                while ((lineText = bufferedReader.readLine()) != null) {
                    if (min != 1) {
                        String[] s = lineText.split("\t");
                        RsCNCsvData rsCNCsvData = RsCNCsvData.toRsCNCsvDataFormat(s);
                        if (rsCNCsvData == null) {
                            continue;
                        }
                        try {
                            if (StringUtils.isEmpty(rsCNCsvData.getStockQtyGb()) && StringUtils.isEmpty(rsCNCsvData.getStockQtyCN())) {
                                continue;
                            }
                            if (!StringUtils.isEmpty(rsCNCsvData.getStockQtyGb())) {//判断中国数据中如果有香港库存做处理
                                RsHkCsvData rsHkCsvData = RsHkCsvData.toRsHkCsvDataFormat(s);
                                CmsGoodsPojo cmsGoodsPojo = insertHKDataToDatabase(rsHkCsvData, isCN, supplierId);
                                if (cmsGoodsPojo != null) {
                                    HispData.add(cmsGoodsPojo.getCmsGoodsEntity().getHisp());
                                    if (rsHKData.get(cmsGoodsPojo.getCmsGoodsEntity().getGoodid()) != null) {//判断当前map当中存在此key
                                        CmsGoodsPojo cmsHKGoodsPojo = (CmsGoodsPojo) rsHKData.get(cmsGoodsPojo.getCmsGoodsEntity().getGoodid());
                                        Object prices = cmsHKGoodsPojo.getCmsGoodsEntity().getPrices();//获取重复的香港阶梯价
                                        cmsGoodsPojo.getCmsGoodsEntity().setPrices(prices);//阶梯价替换
                                        rsHKData.del(cmsGoodsPojo.getCmsGoodsEntity().getGoodid());
                                        objectMaster.add(cmsGoodsPojo);//把替换成功的中国香港数据添加
                                    } else {//rsHKData中没有直接进行添加
                                        objectMaster.add(cmsGoodsPojo);
                                    }
                                }
                            }
                            if (!StringUtils.isEmpty(rsCNCsvData.getStockQtyCN())) {//判断中国数据中如果有中国库存做处理
                                //进行中国数据处理
                                CmsGoodsPojo cmsGoodsPojo = insertCNDataToDatabase(rsCNCsvData, supplierId);
                                objectMaster.add(cmsGoodsPojo);//进行添加
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    min++;
                }

            }
        }
        rsHKData.delAll();
        mapCNHK.clear();
        mapCN.clear();
        // 退出标志
        objectMaster.isBegin = false;
        log.info("rs数据包导入结束");
    }

    /**
     * Rs中国数据入库
     *
     * @param rsCNCsvData RS Components数据解析
     */
    private CmsGoodsPojo insertCNDataToDatabase(RsCNCsvData rsCNCsvData, Integer supplierId) {
        CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();
        CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity(); //商品表数据
        cmsGoodsEntity.setAdminid(0);
        cmsGoodsEntity.setTenantsid(0);
        cmsGoodsEntity.setSupplier(supplierId);
        // 产品唯一标识
        String sign = RsSteppedPriceConstant.CN + rsCNCsvData.getDistributorPartNumber();
        String incodes = EasyExcelUtils.getIncodes(sign, SUPPLIER_ID, cmsGoodsEntity.getSupplier());
        if (mapCN.containsKey(incodes)) {
            return null;
        } else {
            mapCN.put(incodes, new AtomicInteger(0));
        }
        cmsGoodsEntity.setIncodes(incodes);
        cmsGoodsEntity.setGoodid(incodes);
        cmsGoodsEntity.setClassifyid(0);
        if (StringUtils.isEmpty(rsCNCsvData.getImageUrl())) {
            cmsGoodsEntity.setImg("");
        } else {
            cmsGoodsEntity.setImg(rsCNCsvData.getImageUrl());
        }
        cmsGoodsEntity.setType(0);
        cmsGoodsEntity.setStatus(1);
        cmsGoodsEntity.setStatusMsg(null);
        cmsGoodsEntity.setDataType(1);
        cmsGoodsEntity.setModel(rsCNCsvData.getManufacturerPartNumber());//型号
        String manufacturer = rsCNCsvData.getManufacturer();//制造商
        // 处理品牌信息，缓存中没有当前品牌时添加信息到数据库和缓存中
        Integer i = brandCache.get(manufacturer);
        if (i == null) {
            CmsBrandsTempEntity entity = new CmsBrandsTempEntity();
            entity.setName(manufacturer);
            entity.setTag(BrandTagEnum.NEW.getCode());
            CacheUtil.Cache brands = CacheUtil.init(CachePrefixEnum.BRAND.getKey());
            Integer brandId = brands.insertAndGet(entity);
            cmsGoodsEntity.setBrand(brandId);
        } else {
            cmsGoodsEntity.setBrand(i);
        }
        cmsGoodsEntity.setIsSampleApply(0);
        cmsGoodsEntity.setBatch("");
        cmsGoodsEntity.setOriginalPrice(BigDecimal.ZERO);//原价
        cmsGoodsEntity.setPurchasePrice(BigDecimal.ZERO);//进价
        cmsGoodsEntity.setUnitPrice(0D);//单价
        if (StringUtils.isEmpty(rsCNCsvData.getStockQtyCN())) {//为空
            cmsGoodsEntity.setRepertory(0);
        } else {
            cmsGoodsEntity.setRepertory(Integer.valueOf(rsCNCsvData.getStockQtyCN()));//中国库存
        }
        cmsGoodsEntity.setHongkongDate("");
        cmsGoodsEntity.setDomesticDate("5-7工作日");//中国交货时间
        cmsGoodsEntity.setRepertoryArea("上海");//库房所在地
        cmsGoodsEntity.setPublish(1);
        cmsGoodsEntity.setPayType(0);  // 购买类型0单个买1整包买
        // 最小起订
        String priceQuantity = rsCNCsvData.getPriceQuantity();
        String[] split = priceQuantity.split("\\|");
        cmsGoodsEntity.setMinimumOrder(Long.valueOf(split[0]));//最小起订量
        cmsGoodsEntity.setIncremental(1L);
        cmsGoodsEntity.setMpq(Long.valueOf(rsCNCsvData.getPackSize()));// mpq
        // 交货地区
        cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.DOMESTIC.getCode());
        // 是否需要3c认证
        cmsGoodsEntity.setCcc(WhetherOrNotEnum.NO.getCode());
        cmsGoodsEntity.setSales(0);
        cmsGoodsEntity.setClick(0);
        cmsGoodsEntity.setVisitor(0);
        //描述
        cmsGoodsEntity.setDescribe("");
        //商品主图
        cmsGoodsEntity.setAtlas("");
        //商品详情
        cmsGoodsEntity.setContent("");
        if (StringUtils.isEmpty(rsCNCsvData.getRohs())) {
            cmsGoodsEntity.setHisp("");
        } else {
            cmsGoodsEntity.setHisp(rsCNCsvData.getRohs());
        }
        JSONObject json = new JSONObject();
        json.put(rsCNCsvData.getAttributeName1(), rsCNCsvData.getAttributeValue1());
        json.put(rsCNCsvData.getAttributeName2(), rsCNCsvData.getAttributeValue2());
        json.put(rsCNCsvData.getAttributeName3(), rsCNCsvData.getAttributeValue3());
        json.put(rsCNCsvData.getAttributeName4(), rsCNCsvData.getAttributeValue4());
        json.put(rsCNCsvData.getAttributeName5(), rsCNCsvData.getAttributeValue5());
        json.put(rsCNCsvData.getAttributeName6(), rsCNCsvData.getAttributeValue6());
        json.put(rsCNCsvData.getAttributeName7(), rsCNCsvData.getAttributeValue7());
        json.put(rsCNCsvData.getAttributeName8(), rsCNCsvData.getAttributeValue8());
        json.put(rsCNCsvData.getAttributeName9(), rsCNCsvData.getAttributeValue9());
        json.put(rsCNCsvData.getAttributeName10(), rsCNCsvData.getAttributeValue10());
        json.put(rsCNCsvData.getAttributeName11(), rsCNCsvData.getAttributeValue11());
        json.put(rsCNCsvData.getAttributeName12(), rsCNCsvData.getAttributeValue12());
        json.put(rsCNCsvData.getAttributeName13(), rsCNCsvData.getAttributeValue13());
        json.put(rsCNCsvData.getAttributeName14(), rsCNCsvData.getAttributeValue14());
        json.put(rsCNCsvData.getAttributeName15(), rsCNCsvData.getAttributeValue15());
        cmsGoodsEntity.setParams(json.toJSONString());//参数
        cmsGoodsEntity.setCreatedAt(DateUtils.now());
        cmsGoodsEntity.setUpdatedAt(DateUtils.now());
        cmsGoodsEntity.setSource(SourceEnum.DATA_PACKAGE.getCode());
        cmsGoodsEntity.setSplName(SUPPLIER);
        cmsGoodsEntity.setBrandName(manufacturer);
        if (null == cmsGoodsEntity.getMinimumOrder() || cmsGoodsEntity.getMinimumOrder().intValue() == 0) {
            cmsGoodsEntity.setMinimumOrder(1L);
        }
        // 组装阶梯价格信息
        List<CmsPricesEntity> list = createCNCmsPrices(rsCNCsvData, incodes);
        cmsGoodsPojo.setCmsPricesEntityList(list);

        List<CmsPricesPojo> prices = new ArrayList<>();
        for (CmsPricesEntity cmsPricesEntity : list) {
            CmsPricesPojo cmsPricesPojo = new CmsPricesPojo();
            BeanUtils.copyProperties(cmsPricesEntity, cmsPricesPojo);
            prices.add(cmsPricesPojo);
        }
        // 更新阶梯价格配置到商品表
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(prices, SerializerFeature.WriteMapNullValue));
        if (!jsonArray.isEmpty()) {
            cmsGoodsEntity.setPrices(jsonArray.toString());
        }
        // 费率
        JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());

        // 费率信息
        JSONObject jsonObject = (JSONObject) data.get(RateCalculateConstants.RATE);

        cmsGoodsEntity.setRates(jsonObject);
        if (jsonObject != null && !jsonObject.isEmpty()) {
            // 关税率
            String tariffsRate = jsonObject.getString(RateCalculateConstants.TARIFFRATE_FIELD);
            cmsGoodsEntity.setTariffsRate(Double.valueOf(tariffsRate));

            // 商检费
            String ciqPrice = jsonObject.getString(RateCalculateConstants.CIQPRICE_FIELD);
            cmsGoodsEntity.setInspectionChargesFee(Double.valueOf(ciqPrice));
        }
        cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);
        // 组装商品表-副表信息
        cmsGoodsPojo.setCmsGoodsInformationEntity(createCmsGoodsInformation(incodes));
        return cmsGoodsPojo;
    }


    /**
     * Rs香港数据入库
     *
     * @param rsHkCsvData RS Components数据解析
     */
    private CmsGoodsPojo insertHKDataToDatabase(RsHkCsvData rsHkCsvData, Boolean isCN, Integer supplierId) {
        CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();
        if (isCN == false) {//因是香港数据包只封装对象而不入库(只存goodid跟阶梯价)
            CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity(); //商品表数据
//            cmsGoodsEntity.setAdminid(0);
//            cmsGoodsEntity.setTenantsid(0);
            cmsGoodsEntity.setSupplier(supplierId);
            String sign = RsSteppedPriceConstant.HK + rsHkCsvData.getDistributorPartNumber();
            String incodes = EasyExcelUtils.getIncodes(sign, SUPPLIER_ID, cmsGoodsEntity.getSupplier());
            if (mapHK.containsKey(incodes)) {
                return null;
            } else {
                mapHK.put(incodes, new AtomicInteger(0));
            }
            cmsGoodsEntity.setIncodes(incodes);
            cmsGoodsEntity.setGoodid(incodes);
//            cmsGoodsEntity.setClassifyid(0);
//            if (StringUtils.isEmpty(rsHkCsvData.getImageUrl())) {
//                cmsGoodsEntity.setImg("");
//            } else {
//                cmsGoodsEntity.setImg(rsHkCsvData.getImageUrl());
//            }
//            cmsGoodsEntity.setType(0);
//            cmsGoodsEntity.setStatus(1);
//            cmsGoodsEntity.setStatusMsg(null);
//            cmsGoodsEntity.setDataType(1);
//            cmsGoodsEntity.setModel(rsHkCsvData.getManufacturerPartNumber());//型号
//            String manufacturer = rsHkCsvData.getManufacturer();
//            if (StringUtils.isEmpty(manufacturer)) {
//                return null;
//            }
//            cmsGoodsEntity.setBrand(0);//随便赋值不入库
//            cmsGoodsEntity.setIsSampleApply(0);
//            cmsGoodsEntity.setBatch("");
//            cmsGoodsEntity.setOriginalPrice(BigDecimal.ZERO);//原价
//            cmsGoodsEntity.setPurchasePrice(BigDecimal.ZERO);//进价
//            cmsGoodsEntity.setUnitPrice(0D);//单价
//            if (StringUtils.isEmpty(rsHkCsvData.getStockQtyGb())) {//判断香港库存为空给默认值
//                cmsGoodsEntity.setRepertory(0);
//            } else {
//                cmsGoodsEntity.setRepertory(Integer.valueOf(rsHkCsvData.getStockQtyGb()));//香港库存
//            }
//            cmsGoodsEntity.setHongkongDate("12-15工作日");//交货时间
//            cmsGoodsEntity.setDomesticDate("12-15工作日");
//            cmsGoodsEntity.setRepertoryArea("英国");//库房所在地
//            cmsGoodsEntity.setPublish(1);
//            cmsGoodsEntity.setPayType(0);  // 购买类型0单个买1整包买
//            // 最小起订
//            String priceQuantity = rsHkCsvData.getPriceQuantity();
//            String[] split = priceQuantity.split("\\|");
//            cmsGoodsEntity.setMinimumOrder(Integer.valueOf(split[0]));//最小起订量
//            cmsGoodsEntity.setIncremental(1);
//            cmsGoodsEntity.setMpq(Integer.valueOf(rsHkCsvData.getPackSize()));// mpq
//            // 交货地区
//            cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());
//            // 是否需要3c认证
//            cmsGoodsEntity.setCcc(WhetherOrNotEnum.NO.getCode());
//            cmsGoodsEntity.setSales(0);
//            cmsGoodsEntity.setClick(0);
//            cmsGoodsEntity.setVisitor(0);
//            //描述
//            cmsGoodsEntity.setDescribe("");
//            //商品主图
//            cmsGoodsEntity.setAtlas("");
//            //商品详情
//            cmsGoodsEntity.setContent("");
//            if (StringUtils.isEmpty(rsHkCsvData.getRohs())) {
//                cmsGoodsEntity.setHisp("");
//            } else {
//                cmsGoodsEntity.setHisp(rsHkCsvData.getRohs());
//            }
//            JSONObject json = new JSONObject();
//            json.put(rsHkCsvData.getAttributeName1(), rsHkCsvData.getAttributeValue1());
//            json.put(rsHkCsvData.getAttributeName2(), rsHkCsvData.getAttributeValue2());
//            json.put(rsHkCsvData.getAttributeName3(), rsHkCsvData.getAttributeValue3());
//            json.put(rsHkCsvData.getAttributeName4(), rsHkCsvData.getAttributeValue4());
//            json.put(rsHkCsvData.getAttributeName5(), rsHkCsvData.getAttributeValue5());
//            json.put(rsHkCsvData.getAttributeName6(), rsHkCsvData.getAttributeValue6());
//            json.put(rsHkCsvData.getAttributeName7(), rsHkCsvData.getAttributeValue7());
//            json.put(rsHkCsvData.getAttributeName8(), rsHkCsvData.getAttributeValue8());
//            json.put(rsHkCsvData.getAttributeName9(), rsHkCsvData.getAttributeValue9());
//            json.put(rsHkCsvData.getAttributeName10(), rsHkCsvData.getAttributeValue10());
//            json.put(rsHkCsvData.getAttributeName11(), rsHkCsvData.getAttributeValue11());
//            json.put(rsHkCsvData.getAttributeName12(), rsHkCsvData.getAttributeValue12());
//            json.put(rsHkCsvData.getAttributeName13(), rsHkCsvData.getAttributeValue13());
//            json.put(rsHkCsvData.getAttributeName14(), rsHkCsvData.getAttributeValue14());
//            json.put(rsHkCsvData.getAttributeName15(), rsHkCsvData.getAttributeValue15());
//            cmsGoodsEntity.setParams(json.toJSONString());//参数
//            cmsGoodsEntity.setCreatedAt(DateUtils.now());
//            cmsGoodsEntity.setUpdatedAt(DateUtils.now());
//            cmsGoodsEntity.setSource(SourceEnum.DATA_PACKAGE.getCode());
//            cmsGoodsEntity.setSplName(SUPPLIER);
//            cmsGoodsEntity.setBrandName(manufacturer);
//            if (null == cmsGoodsEntity.getMinimumOrder() || cmsGoodsEntity.getMinimumOrder().intValue() == 0) {
//                cmsGoodsEntity.setMinimumOrder(1);
//            }
            // 组装阶梯价格信息
            List<CmsPricesEntity> list = createHKCmsPrices(rsHkCsvData, isCN, incodes);
            cmsGoodsPojo.setCmsPricesEntityList(list);

            List<CmsPricesPojo> prices = new ArrayList<>();
            for (CmsPricesEntity cmsPricesEntity : list) {
                CmsPricesPojo cmsPricesPojo = new CmsPricesPojo();
                BeanUtils.copyProperties(cmsPricesEntity, cmsPricesPojo);
                prices.add(cmsPricesPojo);
            }
            // 更新阶梯价格配置到商品表
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(prices, SerializerFeature.WriteMapNullValue));
            if (!jsonArray.isEmpty()) {
                cmsGoodsEntity.setPrices(jsonArray.toString());
            }
//            // 费率
//            String rate = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());
//            cmsGoodsEntity.setRates(rate);
//            JSONObject jsonObject = JSON.parseObject(rate);
//            if (jsonObject != null && !jsonObject.isEmpty()) {
//                // 关税率
//                String tariffsRate = jsonObject.getString(RateCalculateConstants.TARIFFRATE_FIELD);
//                cmsGoodsEntity.setTariffsRate(Double.valueOf(tariffsRate).intValue());
//
//                // 商检费
//                String ciqPrice = jsonObject.getString(RateCalculateConstants.CIQPRICE_FIELD);
//                cmsGoodsEntity.setInspectionChargesFee(new BigDecimal(ciqPrice));
//            }
            cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);
//
//            // 组装商品表-副表信息
//            cmsGoodsPojo.setCmsGoodsInformationEntity(createCmsGoodsInformation(incodes));
            return cmsGoodsPojo;
        } else {//中国包的香港数据
            CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity(); //商品表数据
            cmsGoodsEntity.setAdminid(0);
            cmsGoodsEntity.setTenantsid(0);
            cmsGoodsEntity.setSupplier(supplierId);
            String sign = RsSteppedPriceConstant.HK + rsHkCsvData.getDistributorPartNumber();
            String incodes = EasyExcelUtils.getIncodes(sign, SUPPLIER_ID, cmsGoodsEntity.getSupplier());
            if (mapCNHK.containsKey(incodes)) {
                return null;
            } else {
                mapCNHK.put(incodes, new AtomicInteger(0));
            }
            cmsGoodsEntity.setIncodes(incodes);
            cmsGoodsEntity.setGoodid(incodes);
            cmsGoodsEntity.setClassifyid(0);
            if (StringUtils.isEmpty(rsHkCsvData.getImageUrl())) {
                cmsGoodsEntity.setImg("");
            } else {
                cmsGoodsEntity.setImg(rsHkCsvData.getImageUrl());
            }
            cmsGoodsEntity.setType(0);
            cmsGoodsEntity.setStatus(1);
            cmsGoodsEntity.setStatusMsg(null);
            cmsGoodsEntity.setDataType(1);
            cmsGoodsEntity.setModel(rsHkCsvData.getManufacturerPartNumber());//型号
            String manufacturer = rsHkCsvData.getManufacturer();
            if (StringUtils.isEmpty(manufacturer)) {
                return null;
            }
            // 处理品牌信息，缓存中没有当前品牌时添加信息到数据库和缓存中
            Integer data = brandCache.get(manufacturer);
            if (data == null) {
                CmsBrandsTempEntity entity = new CmsBrandsTempEntity();
                entity.setName(manufacturer);
                entity.setTag(BrandTagEnum.NEW.getCode());
                CacheUtil.Cache brands = CacheUtil.init(CachePrefixEnum.BRAND.getKey());
                Integer brandId = brands.insertAndGet(entity);
                cmsGoodsEntity.setBrand(brandId);
            } else {
                cmsGoodsEntity.setBrand(data);
            }
            cmsGoodsEntity.setIsSampleApply(0);
            cmsGoodsEntity.setBatch("");
            cmsGoodsEntity.setOriginalPrice(BigDecimal.ZERO);//原价
            cmsGoodsEntity.setPurchasePrice(BigDecimal.ZERO);//进价
            cmsGoodsEntity.setUnitPrice(0D);//单价
            if (StringUtils.isEmpty(rsHkCsvData.getStockQtyGb())) {//判断香港库存为空给默认值
                cmsGoodsEntity.setRepertory(0);
            } else {
                cmsGoodsEntity.setRepertory(Integer.valueOf(rsHkCsvData.getStockQtyGb()));//香港库存
            }
            cmsGoodsEntity.setHongkongDate("12-15工作日");//交货时间
            cmsGoodsEntity.setDomesticDate("12-15工作日");
            cmsGoodsEntity.setRepertoryArea("英国");//库房所在地
            cmsGoodsEntity.setPublish(1);
            cmsGoodsEntity.setPayType(0);  // 购买类型0单个买1整包买
            // 最小起订
            String priceQuantity = rsHkCsvData.getPriceQuantity();
            String[] split = priceQuantity.split("\\|");
            cmsGoodsEntity.setMinimumOrder(Long.valueOf(split[0]));//最小起订量
            cmsGoodsEntity.setIncremental(1L);
            cmsGoodsEntity.setMpq(Long.valueOf(rsHkCsvData.getPackSize()));// mpq
            // 交货地区
            cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());
            // 是否需要3c认证
            cmsGoodsEntity.setCcc(WhetherOrNotEnum.NO.getCode());
            cmsGoodsEntity.setSales(0);
            cmsGoodsEntity.setClick(0);
            cmsGoodsEntity.setVisitor(0);
            //描述
            cmsGoodsEntity.setDescribe("");
            //商品主图
            cmsGoodsEntity.setAtlas("");
            //商品详情
            cmsGoodsEntity.setContent("");
            if (StringUtils.isEmpty(rsHkCsvData.getRohs())) {
                cmsGoodsEntity.setHisp("");
            } else {
                cmsGoodsEntity.setHisp(rsHkCsvData.getRohs());
            }
            JSONObject json = new JSONObject();
            json.put(rsHkCsvData.getAttributeName1(), rsHkCsvData.getAttributeValue1());
            json.put(rsHkCsvData.getAttributeName2(), rsHkCsvData.getAttributeValue2());
            json.put(rsHkCsvData.getAttributeName3(), rsHkCsvData.getAttributeValue3());
            json.put(rsHkCsvData.getAttributeName4(), rsHkCsvData.getAttributeValue4());
            json.put(rsHkCsvData.getAttributeName5(), rsHkCsvData.getAttributeValue5());
            json.put(rsHkCsvData.getAttributeName6(), rsHkCsvData.getAttributeValue6());
            json.put(rsHkCsvData.getAttributeName7(), rsHkCsvData.getAttributeValue7());
            json.put(rsHkCsvData.getAttributeName8(), rsHkCsvData.getAttributeValue8());
            json.put(rsHkCsvData.getAttributeName9(), rsHkCsvData.getAttributeValue9());
            json.put(rsHkCsvData.getAttributeName10(), rsHkCsvData.getAttributeValue10());
            json.put(rsHkCsvData.getAttributeName11(), rsHkCsvData.getAttributeValue11());
            json.put(rsHkCsvData.getAttributeName12(), rsHkCsvData.getAttributeValue12());
            json.put(rsHkCsvData.getAttributeName13(), rsHkCsvData.getAttributeValue13());
            json.put(rsHkCsvData.getAttributeName14(), rsHkCsvData.getAttributeValue14());
            json.put(rsHkCsvData.getAttributeName15(), rsHkCsvData.getAttributeValue15());
            cmsGoodsEntity.setParams(json.toJSONString());//参数
            cmsGoodsEntity.setCreatedAt(DateUtils.now());
            cmsGoodsEntity.setUpdatedAt(DateUtils.now());
            cmsGoodsEntity.setSource(SourceEnum.DATA_PACKAGE.getCode());
            cmsGoodsEntity.setSplName(SUPPLIER);
            cmsGoodsEntity.setBrandName(manufacturer);
            if (null == cmsGoodsEntity.getMinimumOrder() || cmsGoodsEntity.getMinimumOrder().intValue() == 0) {
                cmsGoodsEntity.setMinimumOrder(1L);
            }
            // 组装阶梯价格信息
            List<CmsPricesEntity> list = createHKCmsPrices(rsHkCsvData, isCN, incodes);
            cmsGoodsPojo.setCmsPricesEntityList(list);

            List<CmsPricesPojo> prices = new ArrayList<>();
            for (CmsPricesEntity cmsPricesEntity : list) {
                CmsPricesPojo cmsPricesPojo = new CmsPricesPojo();
                BeanUtils.copyProperties(cmsPricesEntity, cmsPricesPojo);
                prices.add(cmsPricesPojo);
            }
            // 更新阶梯价格配置到商品表
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(prices, SerializerFeature.WriteMapNullValue));
            if (!jsonArray.isEmpty()) {
                cmsGoodsEntity.setPrices(jsonArray.toString());
            }

            // 费率
            JSONObject dataJson = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());
            // 费率信息
            JSONObject jsonObject = (JSONObject) dataJson.get(RateCalculateConstants.RATE);
            cmsGoodsEntity.setRates(jsonObject);
            if (jsonObject != null && !jsonObject.isEmpty()) {
                // 关税率
                String tariffsRate = jsonObject.getString(RateCalculateConstants.TARIFFRATE_FIELD);
//                cmsGoodsEntity.setTariffsRate(Double.valueOf(tariffsRate).intValue());

                // 商检费
                String ciqPrice = jsonObject.getString(RateCalculateConstants.CIQPRICE_FIELD);
//                cmsGoodsEntity.setInspectionChargesFee(new BigDecimal(ciqPrice));
            }
            cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);

            // 组装商品表-副表信息
            cmsGoodsPojo.setCmsGoodsInformationEntity(createCmsGoodsInformation(incodes));
            return cmsGoodsPojo;
        }
    }

    /**
     * 组装阶梯价格信息 中国
     *
     * @param rsCNCsvData RS Components数据解析
     */
    private List<CmsPricesEntity> createCNCmsPrices(RsCNCsvData rsCNCsvData, String goodid) {
        List<CmsPricesEntity> result = new ArrayList<>();
        HashMap<String, String> map = new HashMap<>();
        String priceQuantity = rsCNCsvData.getPriceQuantity();//获取阶梯数量
        String[] split = priceQuantity.split("\\|");//所有订购量

        String hkdPrice1 = rsCNCsvData.getHkdPrice1();//第一阶级价格
        String hkdPrice2 = rsCNCsvData.getHkdPrice2();//第二阶级价格
        String hkdPrice3 = rsCNCsvData.getHkdPrice3();//第三阶级价格
        String hkdPrice4 = rsCNCsvData.getHkdPrice4();//第四阶级价格
        String hkdPrice5 = rsCNCsvData.getHkdPrice5();//第五阶级价格
        int position = 0;
        int max;

        int a = 1;
        for (String data : split) {
            map.put(RsSteppedPriceConstant.CN + a++, data);
        }

        // 一级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.CN1)) && !Strings.isEmpty(hkdPrice1)) {

            if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.CN2))) {
                max = Integer.valueOf(map.get(RsSteppedPriceConstant.CN2)) - 1;
            } else {
                max = 0;
            }

            result.add(createCNCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.CN1)), max, hkdPrice1, CurrencyEnum.RMB.getCode(), position, goodid));
            position = position + 1;
        }

        // 二级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.CN2)) && !Strings.isEmpty(hkdPrice2)) {

            if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.CN3))) {
                max = Integer.valueOf(map.get(RsSteppedPriceConstant.CN3)) - 1;
            } else {
                max = 0;
            }

            result.add(createCNCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.CN2)), max, hkdPrice2, CurrencyEnum.RMB.getCode(), position, goodid));
            position = position + 1;
        }

        // 三级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.CN3)) && !Strings.isEmpty(hkdPrice3)) {

            if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.CN4))) {
                max = Integer.valueOf(map.get(RsSteppedPriceConstant.CN4)) - 1;
                ;
            } else {
                max = 0;
            }

            result.add(createCNCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.CN3)), max, hkdPrice3, CurrencyEnum.RMB.getCode(), position, goodid));
            position = position + 1;
        }

        // 四级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.CN4)) && !Strings.isEmpty(hkdPrice4)) {

            if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.CN5))) {
                max = Integer.valueOf(map.get(RsSteppedPriceConstant.CN5)) - 1;
            } else {
                max = 0;
            }

            result.add(createCNCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.CN4)), max, hkdPrice4, CurrencyEnum.RMB.getCode(), position, goodid));
            position = position + 1;
        }

        // 五级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.CN5)) && !Strings.isEmpty(hkdPrice5)) {
            result.add(createCNCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.CN5)), 0, hkdPrice5, CurrencyEnum.RMB.getCode(), position, goodid));
        }
        return result;

    }


    /**
     * 组装阶梯价格信息 香港
     *
     * @param rsHkCsvData RS Components数据解析
     */
    private List<CmsPricesEntity> createHKCmsPrices(RsHkCsvData rsHkCsvData, Boolean isCN, String goodid) {
        List<CmsPricesEntity> result = new ArrayList<>();
        HashMap<String, String> map = new HashMap<>();
        String priceQuantity = rsHkCsvData.getPriceQuantity();//获取阶梯数量
        String[] split = priceQuantity.split("\\|");//所有订购量
        String hkdPrice1 = rsHkCsvData.getHkdPrice1();//第一阶级价格
        String hkdPrice2 = rsHkCsvData.getHkdPrice2();//第二阶级价格
        String hkdPrice3 = rsHkCsvData.getHkdPrice3();//第三阶级价格
        String hkdPrice4 = rsHkCsvData.getHkdPrice4();//第四阶级价格
        String hkdPrice5 = rsHkCsvData.getHkdPrice5();//第五阶级价格

        int position = 0;
        int max;
        int a = 1;
        for (String data : split) {
            map.put(RsSteppedPriceConstant.HK + a++, data);
        }
        // 一级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.HK1)) && !Strings.isEmpty(hkdPrice1)) {

            if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.HK2))) {
                max = Integer.valueOf(map.get(RsSteppedPriceConstant.HK2)) - 1;
            } else {
                max = 0;
            }

            result.add(createCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.HK1)), max, hkdPrice1, CurrencyEnum.DOLLAR.getCode(), position, isCN, goodid));
            position = position + 1;
        }

        // 二级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.HK2)) && !Strings.isEmpty(hkdPrice2)) {

            if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.HK3))) {
                max = Integer.valueOf(map.get(RsSteppedPriceConstant.HK3)) - 1;
            } else {
                max = 0;
            }

            result.add(createCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.HK2)), max, hkdPrice2, CurrencyEnum.DOLLAR.getCode(), position, isCN, goodid));
            position = position + 1;
        }

        // 三级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.HK3)) && !Strings.isEmpty(hkdPrice3)) {

            if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.HK4))) {
                max = Integer.valueOf(map.get(RsSteppedPriceConstant.HK4)) - 1;
                ;
            } else {
                max = 0;
            }

            result.add(createCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.HK3)), max, hkdPrice3, CurrencyEnum.DOLLAR.getCode(), position, isCN, goodid));
            position = position + 1;
        }

        // 四级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.HK4)) && !Strings.isEmpty(hkdPrice4)) {

            if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.HK5))) {
                max = Integer.valueOf(map.get(RsSteppedPriceConstant.HK5)) - 1;
            } else {
                max = 0;
            }

            result.add(createCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.HK4)), max, hkdPrice4, CurrencyEnum.DOLLAR.getCode(), position, isCN, goodid));
            position = position + 1;
        }

        // 五级阶梯价格
        if (!StringUtils.isEmpty(map.get(RsSteppedPriceConstant.HK5)) && !Strings.isEmpty(hkdPrice5)) {
            result.add(createCmsPriceData(Integer.valueOf(map.get(RsSteppedPriceConstant.HK5)), 0, hkdPrice5, CurrencyEnum.DOLLAR.getCode(), position, isCN, goodid));
        }
        return result;
    }
}


